<template>
  <div class="payment-container">
    <div class="payment-header">
      <h2>订单支付</h2>
      <el-steps :active="currentStep" finish-status="success" simple>
        <el-step title="确认订单" />
        <el-step title="选择支付方式" />
        <el-step title="完成支付" />
      </el-steps>
    </div>

    <!-- 步骤1：确认订单 -->
    <div v-if="currentStep === 0" class="step-content">
      <el-card class="order-info-card">
        <template #header>
          <div class="card-header">
            <span>订单信息</span>
            <el-tag type="warning">待支付</el-tag>
          </div>
        </template>
        
        <div v-if="orderInfo" class="order-details">
          <div class="order-number">
            <span class="label">订单号：</span>
            <span class="value">{{ orderInfo.order.orderNumber }}</span>
          </div>
          
          <div class="order-items">
            <h4>商品信息</h4>
            <div v-for="item in orderInfo.items" :key="item.id" class="order-item">
              <div class="item-image">
                <img :src="item.productImage || '/default-product.jpg'" :alt="item.productName" />
              </div>
              <div class="item-info">
                <div class="item-name">{{ item.productName }}</div>
                <div class="item-price">¥{{ item.price }} × {{ item.quantity }}</div>
              </div>
              <div class="item-subtotal">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
            </div>
          </div>
          
          <!-- 收货地址选择 -->
          <div class="order-address">
            <h4>收货地址</h4>
            <div class="address-selection">
              <el-radio-group v-model="addressType" @change="handleAddressTypeChange">
                <el-radio label="existing">使用现有地址</el-radio>
                <el-radio label="new">输入新地址</el-radio>
              </el-radio-group>
              
              <!-- 现有地址选择 -->
              <div v-if="addressType === 'existing'" class="existing-address">
                <el-select v-model="selectedAddressId" placeholder="请选择收货地址" style="width: 100%; margin-top: 15px;">
                  <el-option
                    v-for="address in userAddresses"
                    :key="address.id"
                    :label="`${address.receiverName} - ${address.province}${address.city}${address.district}${address.detailAddress}`"
                    :value="address.id"
                  />
                </el-select>
                <div v-if="selectedAddress" class="selected-address-info">
                  <p>{{ selectedAddress.receiverName }} {{ selectedAddress.phone }}</p>
                  <p>{{ selectedAddress.province }} {{ selectedAddress.city }} {{ selectedAddress.district }}</p>
                  <p>{{ selectedAddress.detailAddress }}</p>
                </div>
              </div>
              
              <!-- 新地址输入 -->
              <div v-if="addressType === 'new'" class="new-address-form">
                <el-form :model="newAddress" label-width="100px" style="margin-top: 15px;">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="收货人" required>
                        <el-input v-model="newAddress.receiverName" placeholder="请输入收货人姓名" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="手机号" required>
                        <el-input v-model="newAddress.phone" placeholder="请输入手机号" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <el-form-item label="省份" required>
                        <el-input v-model="newAddress.province" placeholder="请输入省份" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="城市" required>
                        <el-input v-model="newAddress.city" placeholder="请输入城市" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="区县" required>
                        <el-input v-model="newAddress.district" placeholder="请输入区县" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item label="详细地址" required>
                    <el-input 
                      v-model="newAddress.detailAddress" 
                      type="textarea" 
                      placeholder="请输入详细地址"
                      :rows="3"
                    />
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </div>
          
          <div class="order-total">
            <div class="total-row">
              <span>商品总额：</span>
              <span>¥{{ orderInfo.order.totalPrice }}</span>
            </div>
            <div class="total-row">
              <span>运费：</span>
              <span>¥0.00</span>
            </div>
            <div class="total-row total-price">
              <span>实付金额：</span>
              <span>¥{{ orderInfo.order.totalPrice }}</span>
            </div>
          </div>
        </div>
        
        <div class="step-actions">
          <el-button @click="$router.go(-1)">返回</el-button>
          <el-button type="primary" @click="nextStep" :loading="loading" :disabled="!isAddressValid">确认订单</el-button>
        </div>
      </el-card>
    </div>

    <!-- 步骤2：选择支付方式 -->
    <div v-if="currentStep === 1" class="step-content">
      <el-card class="payment-method-card">
        <template #header>
          <div class="card-header">
            <span>选择支付方式</span>
          </div>
        </template>
        
        <div class="payment-amount">
          <div class="amount-label">支付金额</div>
          <div class="amount-value">¥{{ orderInfo?.order.totalPrice || '0.00' }}</div>
        </div>
        
        <div class="payment-methods">
          <div 
            v-for="method in paymentMethods" 
            :key="method.value"
            class="payment-method-item"
            :class="{ active: selectedPaymentMethod === method.value }"
            @click="selectedPaymentMethod = method.value"
          >
            <div class="method-icon">
              <el-icon :size="24">
                <component :is="method.icon" />
              </el-icon>
            </div>
            <div class="method-info">
              <div class="method-name">{{ method.name }}</div>
              <div class="method-desc">{{ method.description }}</div>
            </div>
            <div class="method-radio">
              <el-radio v-model="selectedPaymentMethod" :label="method.value" />
            </div>
          </div>
        </div>

        <!-- 支付验证码 -->
        <div v-if="showVerificationCode" class="verification-section">
          <h4>支付验证</h4>
          <div class="verification-info">
            <p>为了确保支付安全，请输入验证码：<strong>{{ verificationCode }}</strong></p>
            <p class="verification-tip">验证码已发送到您的手机，请注意查收</p>
          </div>
          <el-form :model="verificationForm" label-width="100px">
            <el-form-item label="验证码" required>
              <el-input 
                v-model="verificationForm.code" 
                placeholder="请输入验证码"
                maxlength="6"
                show-word-limit
                style="width: 200px;"
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 支付进度 -->
        <div v-if="paymentProgress.show" class="payment-progress">
          <h4>支付处理中</h4>
          <el-progress 
            :percentage="paymentProgress.percentage" 
            :status="paymentProgress.status"
            :stroke-width="8"
          />
          <p class="progress-text">{{ paymentProgress.text }}</p>
        </div>
        
        <div class="step-actions">
          <el-button @click="prevStep">上一步</el-button>
          <el-button 
            v-if="!showVerificationCode && !paymentProgress.show"
            type="primary" 
            @click="initiatePayment" 
            :loading="paying"
          >
            立即支付
          </el-button>
          <el-button 
            v-if="showVerificationCode && !paymentProgress.show"
            type="primary" 
            @click="confirmPayment" 
            :loading="paying"
            :disabled="!verificationForm.code || verificationForm.code.length !== 6"
          >
            确认支付
          </el-button>
          <el-button 
            v-if="paymentProgress.show"
            type="danger" 
            @click="cancelPayment"
            :disabled="paymentProgress.percentage > 80"
          >
            取消支付
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 步骤3：支付结果 -->
    <div v-if="currentStep === 2" class="step-content">
      <el-card class="payment-result-card">
        <div class="payment-result">
          <div class="result-icon">
            <el-icon :size="64" color="#67c23a">
              <CircleCheckFilled />
            </el-icon>
          </div>
          <div class="result-title">支付成功</div>
          <div class="result-desc">您的订单已支付成功，我们会尽快为您发货</div>
          <div class="result-info">
            <p>订单号：{{ orderInfo?.order.orderNumber }}</p>
            <p>支付金额：¥{{ orderInfo?.order.totalPrice }}</p>
            <p>支付时间：{{ paymentTime }}</p>
            <p>支付方式：{{ getPaymentMethodName(selectedPaymentMethod) }}</p>
          </div>
        </div>
        
        <div class="step-actions">
          <el-button @click="$router.push('/orders')">查看订单</el-button>
          <el-button type="primary" @click="$router.push('/products')">继续购物</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { CircleCheckFilled, CreditCard, Wallet } from '@element-plus/icons-vue';
import request from '@/utils/request';

export default {
  name: 'PaymentPage',
  components: {
    CircleCheckFilled,
    CreditCard,
    Wallet
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    
    const currentStep = ref(0);
    const orderInfo = ref(null);
    const selectedPaymentMethod = ref(0);
    const loading = ref(false);
    const paying = ref(false);
    const paymentTime = ref('');
    
    // 地址相关
    const addressType = ref('existing');
    const userAddresses = ref([]);
    const selectedAddressId = ref(null);
    const newAddress = ref({
      receiverName: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      detailAddress: ''
    });

    // 支付验证相关
    const showVerificationCode = ref(false);
    const verificationCode = ref('');
    const verificationForm = ref({
      code: ''
    });

    // 支付进度相关
    const paymentProgress = ref({
      show: false,
      percentage: 0,
      status: '',
      text: ''
    });

    const paymentMethods = [
      {
        value: 0,
        name: '支付宝',
        description: '推荐有支付宝账户的用户使用',
        icon: 'Wallet'
      },
      {
        value: 1,
        name: '微信支付',
        description: '推荐有微信账户的用户使用',
        icon: 'CreditCard'
      },
      {
        value: 2,
        name: '银行卡支付',
        description: '支持各大银行储蓄卡和信用卡',
        icon: 'CreditCard'
      }
    ];

    // 计算属性
    const selectedAddress = computed(() => {
      return userAddresses.value.find(addr => addr.id === selectedAddressId.value);
    });

    const isAddressValid = computed(() => {
      if (addressType.value === 'existing') {
        return selectedAddressId.value !== null;
      } else {
        return newAddress.value.receiverName && 
               newAddress.value.phone && 
               newAddress.value.province && 
               newAddress.value.city && 
               newAddress.value.district && 
               newAddress.value.detailAddress;
      }
    });

    const fetchOrderInfo = async () => {
      const orderId = route.params.orderId;
      if (!orderId) {
        ElMessage.error('订单ID不能为空');
        router.push('/orders');
        return;
      }

      loading.value = true;
      try {
        const response = await request.get(`/orders/${orderId}`, {
          params: { userId: localStorage.getItem('userId') }
        });
        
        if (response.code === 200) {
          orderInfo.value = response.data;
        } else {
          ElMessage.error(response.message || '获取订单信息失败');
          router.push('/orders');
        }
      } catch (error) {
        ElMessage.error('获取订单信息失败');
        router.push('/orders');
      } finally {
        loading.value = false;
      }
    };

    const fetchUserAddresses = async () => {
      try {
        const response = await request.get('/address', {
          params: { userId: localStorage.getItem('userId') }
        });
        
        if (response.code === 200) {
          userAddresses.value = response.data || [];
          // 如果有地址，默认选择第一个
          if (userAddresses.value.length > 0) {
            selectedAddressId.value = userAddresses.value[0].id;
          }
        }
      } catch (error) {
        console.error('获取用户地址失败:', error);
      }
    };

    const handleAddressTypeChange = () => {
      if (addressType.value === 'existing' && userAddresses.value.length === 0) {
        ElMessage.warning('您还没有添加收货地址，请先添加地址');
        addressType.value = 'new';
      }
    };

    const nextStep = async () => {
      // 验证地址
      if (!isAddressValid.value) {
        ElMessage.warning('请完善收货地址信息');
        return;
      }

      // 如果是新地址，先保存地址
      if (addressType.value === 'new') {
        try {
          const addressData = {
            ...newAddress.value,
            userId: localStorage.getItem('userId')
          };
          
          const response = await request.post('/address', addressData);
          if (response.code === 200) {
            ElMessage.success('地址保存成功');
            // 更新订单地址
            await updateOrderAddress(response.data.id);
          } else {
            ElMessage.error('地址保存失败');
            return;
          }
        } catch (error) {
          ElMessage.error('地址保存失败');
          return;
        }
      } else {
        // 使用现有地址，更新订单地址
        await updateOrderAddress(selectedAddressId.value);
      }

      currentStep.value++;
    };

    const updateOrderAddress = async (addressId) => {
      try {
        const response = await request.put(`/orders/${route.params.orderId}/address`, null, {
          params: { addressId, userId: localStorage.getItem('userId') }
        });
        
        if (response.code !== 200) {
          ElMessage.error('更新订单地址失败');
        }
      } catch (error) {
        console.error('更新订单地址失败:', error);
      }
    };

    const prevStep = () => {
      currentStep.value--;
    };

    const processPayment = async () => {
      if (selectedPaymentMethod.value === null) {
        ElMessage.warning('请选择支付方式');
        return;
      }

      const orderId = route.params.orderId;
      paying.value = true;
      
      try {
        // 模拟支付延迟
        await new Promise(resolve => setTimeout(resolve, 2000));
        
        const response = await request.post(`/orders/${orderId}/pay`, null, {
          params: { paymentMethod: selectedPaymentMethod.value }
        });
        
        if (response.code === 200) {
          paymentTime.value = new Date().toLocaleString('zh-CN');
          currentStep.value = 2;
          ElMessage.success('支付成功');
          setTimeout(() => {
            router.push('/orders');
          }, 1500);
        } else {
          ElMessage.error(response.message || '支付失败');
        }
      } catch (error) {
        ElMessage.error('支付失败: ' + (error.response?.data?.message || '网络错误'));
      } finally {
        paying.value = false;
      }
    };

    const initiatePayment = async () => {
      if (selectedPaymentMethod.value === null) {
        ElMessage.warning('请选择支付方式');
        return;
      }

      const orderId = route.params.orderId;
      paying.value = true;
      
      try {
        const response = await request.post(`/orders/${orderId}/pay`, null, {
          params: { paymentMethod: selectedPaymentMethod.value }
        });
        
        if (response.code === 200) {
          // 显示验证码
          verificationCode.value = response.data.verificationCode || '123456';
          showVerificationCode.value = true;
          ElMessage.success('请查看验证码并完成支付');
        } else {
          ElMessage.error(response.message || '支付初始化失败');
        }
      } catch (error) {
        ElMessage.error('支付初始化失败: ' + (error.response?.data?.message || '网络错误'));
      } finally {
        paying.value = false;
      }
    };

    const confirmPayment = async () => {
      if (!verificationForm.value.code || verificationForm.value.code.length !== 6) {
        ElMessage.warning('请输入6位验证码');
        return;
      }

      const orderId = route.params.orderId;
      paying.value = true;
      
      try {
        // 验证支付验证码
        const verifyResponse = await request.post(`/orders/${orderId}/verify-payment-code`, null, {
          params: { 
            paymentMethod: selectedPaymentMethod.value,
            verificationCode: verificationForm.value.code
          }
        });
        
        if (verifyResponse.code === 200) {
          // 开始支付进度
          await simulatePaymentProgress();
          paymentTime.value = new Date().toLocaleString('zh-CN');
          currentStep.value = 2;
          ElMessage.success('支付成功');
          setTimeout(() => {
            router.push('/orders');
          }, 1500);
        } else {
          ElMessage.error(verifyResponse.message || '验证码错误');
        }
      } catch (error) {
        ElMessage.error('支付确认失败: ' + (error.response?.data?.message || '网络错误'));
      } finally {
        paying.value = false;
      }
    };

    const simulatePaymentProgress = async () => {
      paymentProgress.value = {
        show: true,
        percentage: 0,
        status: '',
        text: '正在连接支付服务器...'
      };

      // 模拟支付进度
      const steps = [
        { percentage: 20, text: '正在连接支付服务器...' },
        { percentage: 40, text: '正在验证支付信息...' },
        { percentage: 60, text: '正在处理支付请求...' },
        { percentage: 80, text: '正在确认支付结果...' },
        { percentage: 100, text: '支付成功！' }
      ];

      for (let i = 0; i < steps.length; i++) {
        await new Promise(resolve => setTimeout(resolve, 800 + Math.random() * 400));
        paymentProgress.value.percentage = steps[i].percentage;
        paymentProgress.value.text = steps[i].text;
        
        if (i === steps.length - 1) {
          paymentProgress.value.status = 'success';
        }
      }

      // 等待一秒后隐藏进度条
      await new Promise(resolve => setTimeout(resolve, 1000));
      paymentProgress.value.show = false;
    };

    const cancelPayment = async () => {
      try {
        const response = await request.post(`/orders/${route.params.orderId}/cancel-payment`, null, {
          params: { 
            paymentMethod: selectedPaymentMethod.value,
            userId: localStorage.getItem('userId')
          }
        });
        
        if (response.code === 200) {
          ElMessage.success('支付已取消');
          paymentProgress.value.show = false;
          showVerificationCode.value = false;
          verificationForm.value.code = '';
        } else {
          ElMessage.error(response.message || '取消支付失败');
        }
      } catch (error) {
        ElMessage.error('取消支付失败: ' + (error.response?.data?.message || '网络错误'));
      }
    };

    const getPaymentMethodName = (method) => {
      const paymentMethod = paymentMethods.find(m => m.value === method);
      return paymentMethod ? paymentMethod.name : '未知';
    };

    onMounted(() => {
      fetchOrderInfo();
      fetchUserAddresses();
    });

    return {
      currentStep,
      orderInfo,
      selectedPaymentMethod,
      paymentMethods,
      loading,
      paying,
      paymentTime,
      addressType,
      userAddresses,
      selectedAddressId,
      newAddress,
      selectedAddress,
      isAddressValid,
      showVerificationCode,
      verificationCode,
      verificationForm,
      paymentProgress,
      nextStep,
      prevStep,
      processPayment,
      initiatePayment,
      confirmPayment,
      handleAddressTypeChange,
      getPaymentMethodName,
      cancelPayment
    };
  }
};
</script>

<style scoped>
.payment-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.payment-header {
  margin-bottom: 30px;
  text-align: center;
}

.payment-header h2 {
  margin-bottom: 20px;
  color: #303133;
}

.step-content {
  margin-bottom: 20px;
}

.order-info-card,
.payment-method-card,
.payment-result-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-details {
  padding: 20px 0;
}

.order-number {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.order-number .label {
  font-weight: bold;
  color: #606266;
}

.order-number .value {
  color: #303133;
  font-family: monospace;
}

.order-items {
  margin-bottom: 30px;
}

.order-items h4 {
  margin-bottom: 15px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 60px;
  height: 60px;
  margin-right: 15px;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.item-price {
  color: #909399;
  font-size: 14px;
}

.item-subtotal {
  font-weight: bold;
  color: #f56c6c;
  font-size: 16px;
}

.order-address {
  margin-bottom: 30px;
}

.order-address h4 {
  margin-bottom: 15px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.address-selection {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.existing-address,
.new-address-form {
  flex: 1;
}

.selected-address-info {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-top: 15px;
}

.selected-address-info p {
  margin: 5px 0;
  color: #606266;
}

.order-total {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.total-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #606266;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  border-top: 1px solid #ebeef5;
  padding-top: 10px;
  margin-top: 10px;
}

.payment-amount {
  text-align: center;
  margin-bottom: 30px;
  padding: 30px;
  background: #f8f9fa;
  border-radius: 8px;
}

.amount-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.amount-value {
  font-size: 32px;
  font-weight: bold;
  color: #f56c6c;
}

.payment-methods {
  margin-bottom: 30px;
}

.payment-method-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border: 2px solid #ebeef5;
  border-radius: 8px;
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.payment-method-item:hover {
  border-color: #409eff;
}

.payment-method-item.active {
  border-color: #409eff;
  background: #f0f9ff;
}

.method-icon {
  margin-right: 15px;
  color: #409eff;
}

.method-info {
  flex: 1;
}

.method-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.method-desc {
  font-size: 14px;
  color: #909399;
}

.method-radio {
  margin-left: 15px;
}

.verification-section {
  margin-top: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.verification-section h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.verification-info {
  margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #d4edda;
}

.verification-info p {
  margin: 0;
  color: #155724;
}

.verification-info strong {
  color: #f56c6c;
  font-size: 18px;
  letter-spacing: 2px;
}

.verification-tip {
  color: #909399;
  font-size: 14px;
}

.payment-result {
  text-align: center;
  padding: 40px 20px;
}

.result-icon {
  margin-bottom: 20px;
}

.result-title {
  font-size: 24px;
  font-weight: bold;
  color: #67c23a;
  margin-bottom: 10px;
}

.result-desc {
  color: #606266;
  margin-bottom: 30px;
}

.result-info {
  text-align: left;
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.result-info p {
  margin: 10px 0;
  color: #606266;
}

.step-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
}

.payment-progress {
  margin-top: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.payment-progress h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.progress-text {
  color: #909399;
  font-size: 14px;
}
</style> 